#encoding:utf8
import storageconnector
import sharpfs
from connectorset import ConnectorSet

def Upload(dest, src):
    try:
        fsClient = sharpfs.SharpFsSync()
        fsClient.Connect('localhost', 8888)
        token = fsClient.Login('root', 'iamacfan').token
        result = fsClient.CreateFile(token, dest)            
        inode = result.inode
        blockId = result.blockId
        addresses = result.addresses
        
        cs = ConnectorSet(addresses)
        dataTransferred = 0
        with open(src) as f:
            while True:
                data = f.read(4096)
                if data == "":
                    break;
                cs.Write(blockId, data)
                dataTransferred += len(data)
                if dataTransferred > 1024 * 1024:
                    result = fsClient.AddBlock(token, inode)
                    blockId = result.blockId
                    addresses = result.addresses
                    cs = ConnectorSet(addresses)
                    dataTransferred = 0
            fsClient.Logout(token)
    except Exception as err:
        print err
        
def Download(src, dest):
    try:
        fsClient = sharpfs.SharpFsSync()
        fsClient.Connect('localhost', 8888)
        token = fsClient.Login('root', 'iamacfan').token
        result = fsClient.OpenFile(token, src, True)
        inode = result.inode
        with open(dest, 'w') as f:
            for address in result.addresses:
                connector = storageconnector.StorageConnector()
                connector.Connect(address.address, 6666)
                length = connector.GetBlockSize(address.blockId).size
                offset = 0
                while offset < length:
                    result = connector.Read(address.blockId, offset, 4096)
                    offset += result.length
                    f.write(result.data)
                
    except Exception as err:
        print err